﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Microsoft.EntityFrameworkCore;
using ThridGroup.ERP.EntityFrameworkCore;
using ThridGroup.ERP.DTO.SupplierDto;

namespace ThridGroup.ERP.ProductionSystem
{
    /// <summary>
    /// 供应商管理接口实现   ---tsh
    /// </summary>
    public class SupplierModelServices : ApplicationService, ISupplierModelServices
    {
        private readonly IRepository<SupplierModel, int> _supplierRepository;
        private readonly ERPDbContext _dbContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="supplierRepository">供应商仓储</param>
        /// <param name="dbContext">数据库上下文</param>
        public SupplierModelServices(
            IRepository<SupplierModel, int> supplierRepository,
            ERPDbContext dbContext)
        {
            _supplierRepository = supplierRepository;
            _dbContext = dbContext;
        }

        /// <summary>
        /// 获取供应商分页列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>分页结果</returns>
        public async Task<PagedResultDto<SupplierDto>> GetSupplierPagedListAsync(QuerySupplierDto query)
        {
            try
            {
                var queryable = _dbContext.SupplierModels.Where(x => !x.IsDeleted);

                // 条件查询
                if (!string.IsNullOrWhiteSpace(query.SupplierCode))
                {
                    queryable = queryable.Where(x => x.SupplierCode.Contains(query.SupplierCode));
                }

                if (!string.IsNullOrWhiteSpace(query.SupplierName))
                {
                    queryable = queryable.Where(x => x.SupplierName.Contains(query.SupplierName));
                }

                if (!string.IsNullOrWhiteSpace(query.SupplierGrade))
                {
                    queryable = queryable.Where(x => x.SupplierGrade == query.SupplierGrade);
                }

                if (!string.IsNullOrWhiteSpace(query.SupplierPhone))
                {
                    queryable = queryable.Where(x => x.SupplierPhone.Contains(query.SupplierPhone));
                }

                if (query.IsEnable.HasValue)
                {
                    queryable = queryable.Where(x => x.IsEnable == query.IsEnable.Value);
                }

                // 获取总数
                var totalCount = await queryable.CountAsync();

                // 分页查询
                var suppliers = await queryable
                    .OrderByDescending(x => x.Id)
                    .Skip((query.Page - 1) * query.Limit)
                    .Take(query.Limit)
                    .ToListAsync();

                // 转换为DTO
                var supplierDtos = suppliers.Select(x => new SupplierDto
                {
                    Id = x.Id,
                    SupplierCode = x.SupplierCode,
                    SupplierName = x.SupplierName,
                    SupplierGrade = x.SupplierGrade,
                    SupplierScore = x.SupplierScore,
                    SupplierPhone = x.SupplierPhone,
                    IsEnable = x.IsEnable,
                    SupplierAdress = x.SupplierAdress,
                    Context = x.Context
                }).ToList();

                return new PagedResultDto<SupplierDto>(totalCount, supplierDtos);
            }
            catch (Exception ex)
            {
                return new PagedResultDto<SupplierDto>
                {
                    Code = 500,
                    Msg = $"查询失败：{ex.Message}",
                    Count = 0,
                    Data = new List<SupplierDto>()
                };
            }
        }

        /// <summary>
        /// 根据ID获取供应商信息
        /// </summary>
        /// <param name="id">供应商ID</param>
        /// <returns>供应商信息</returns>
        public async Task<SupplierDto> GetSupplierByIdAsync(int id)
        {
            var supplier = await _supplierRepository.GetAsync(id);
            if (supplier == null)
                return null;

            return new SupplierDto
            {
                Id = supplier.Id,
                SupplierCode = supplier.SupplierCode,
                SupplierName = supplier.SupplierName,
                SupplierGrade = supplier.SupplierGrade,
                SupplierScore = supplier.SupplierScore,
                SupplierPhone = supplier.SupplierPhone,
                IsEnable = supplier.IsEnable,
                SupplierAdress = supplier.SupplierAdress,
                Context = supplier.Context
            };
        }

        /// <summary>
        /// 创建供应商
        /// </summary>
        /// <param name="input">创建供应商输入</param>
        /// <returns>创建结果</returns>
        public async Task<bool> CreateSupplierAsync(CreateSupplierDto input)
        {
            try
            {
                // 检查编码是否重复
                var existingSupplier = await _dbContext.SupplierModels
                    .FirstOrDefaultAsync(x => x.SupplierCode == input.SupplierCode && !x.IsDeleted);
                
                if (existingSupplier != null)
                {
                    throw new Exception("供应商编码已存在");
                }

                var supplier = new SupplierModel
                {
                    SupplierCode = input.SupplierCode,
                    SupplierName = input.SupplierName,
                    SupplierGrade = input.SupplierGrade,
                    SupplierScore = input.SupplierScore,
                    SupplierPhone = input.SupplierPhone,
                    IsEnable = input.IsEnable,
                    SupplierAdress = input.SupplierAdress,
                    Context = input.Context,
                    IsDeleted = false
                };

                await _supplierRepository.InsertAsync(supplier);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 更新供应商
        /// </summary>
        /// <param name="input">更新供应商输入</param>
        /// <returns>更新结果</returns>
        public async Task<bool> UpdateSupplierAsync(UpdateSupplierDto input)
        {
            try
            {
                var supplier = await _supplierRepository.GetAsync(input.Id);
                if (supplier == null)
                    return false;

                // 检查编码是否重复（排除自己）
                var existingSupplier = await _dbContext.SupplierModels
                    .FirstOrDefaultAsync(x => x.SupplierCode == input.SupplierCode && x.Id != input.Id && !x.IsDeleted);
                
                if (existingSupplier != null)
                {
                    throw new Exception("供应商编码已存在");
                }

                supplier.SupplierCode = input.SupplierCode;
                supplier.SupplierName = input.SupplierName;
                supplier.SupplierGrade = input.SupplierGrade;
                supplier.SupplierScore = input.SupplierScore;
                supplier.SupplierPhone = input.SupplierPhone;
                supplier.IsEnable = input.IsEnable;
                supplier.SupplierAdress = input.SupplierAdress;
                supplier.Context = input.Context;

                await _supplierRepository.UpdateAsync(supplier);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 删除供应商
        /// </summary>
        /// <param name="id">供应商ID</param>
        /// <returns>删除结果</returns>
        public async Task<bool> DeleteSupplierAsync(int id)
        {
            try
            {
                var supplier = await _supplierRepository.GetAsync(id);
                if (supplier == null)
                    return false;

                // 软删除
                supplier.IsDeleted = true;
                await _supplierRepository.UpdateAsync(supplier);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 自动生成供应商编码
        /// </summary>
        /// <returns>供应商编码</returns>
        public async Task<string> GenerateSupplierCodeAsync()
        {
            // 生成格式：年月日时分秒 (yyyyMMddHHmmss)
            var now = DateTime.Now;
            var baseCode = now.ToString("yyyyMMddHHmmss");
            
            // 检查是否重复，如果重复则添加毫秒
            var existingSupplier = await _dbContext.SupplierModels
                .FirstOrDefaultAsync(x => x.SupplierCode == baseCode && !x.IsDeleted);
            
            if (existingSupplier != null)
            {
                // 如果重复，添加毫秒
                baseCode = now.ToString("yyyyMMddHHmmssfff");
            }
            
            return baseCode;
        }

        /// <summary>
        /// 批量删除供应商
        /// </summary>
        /// <param name="ids">供应商ID列表</param>
        /// <returns>删除结果</returns>
        public async Task<bool> BatchDeleteSupplierAsync(List<int> ids)
        {
            try
            {
                var suppliers = await _dbContext.SupplierModels
                    .Where(x => ids.Contains(x.Id) && !x.IsDeleted)
                    .ToListAsync();

                foreach (var supplier in suppliers)
                {
                    supplier.IsDeleted = true;
                }

                await _dbContext.SaveChangesAsync();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
